#include "repair.h"
#include "ui_repair.h"
#include "dbmanager.h"
#include "entity/repairentity.h"

Repair::Repair(QWidget *parent) :
    QWidget(parent), ui(new Ui::Repair)
{
    ui->setupUi(this);
    connect(ui->addSpButton, SIGNAL(clicked()), this, SLOT(slotAddSpClicked()));
    connect(ui->deleteSpButton, SIGNAL(clicked()), this, SLOT(slotDeleteSpClicked()));
    connect(ui->okButton, SIGNAL(clicked()), this, SLOT(slotOkClicked()));
}

Repair::~Repair()
{
    delete ui;
}

void Repair::slotAddSpClicked()
{
    search = new Search(0);
    search->setTitle("Search Spare Parts");

    connect(search->getOkButton(), SIGNAL(clicked()), this, SLOT(slotSparePartSelected()));
    DBManager * dbm = DBManager::getGlobal();
    model = new QSqlTableModel(search);
    dbm->allSpareParts(model);
    search->getTableView()->setModel(model);
    search->setWindowModality(Qt::ApplicationModal);
    search->show();
}

void Repair::slotSparePartSelected()
{
    QItemSelectionModel * selectionModel = search->getTableView()->selectionModel();
    int selectedRow = selectionModel->currentIndex().row();

    QSqlRecord record = model->record(selectedRow);
    QString item = record.value("sp_code").toString() + " : " + record.value("sp_name").toString();
    if (!spList.contains(item))
    {
        spList[item] = record;
        ui->sparePartList->addItem(item);
    }
}

void Repair::slotDeleteSpClicked()
{
    if (!ui->sparePartList->currentItem())
        return;
    QString item = ui->sparePartList->currentItem()->text();
    bool hasItem = false;
    if (spList.contains(item))
    {
        hasItem = true;
    }
    if (hasItem)
    {
        spList.remove(item);
        ui->sparePartList->takeItem(ui->sparePartList->currentRow());
    }
}

void Repair::slotOkClicked()
{
    QList<int> sparePartList;
    QMapIterator<QString, QSqlRecord> i(spList);

    while (i.hasNext())
    {
        i.next();
        QSqlRecord record = i.value();
        sparePartList.append(record.value("sp_id").toInt());
    }

    RepairEntity * rep = new RepairEntity();
    rep->setRepairCode(ui->repairCodeText->text());
    rep->setRepairName(ui->repairNameText->text());
    rep->setRepairDesc(ui->descText->toPlainText());
    rep->setSpList(sparePartList);
    rep->setDeleted(0);

    DBManager * dbm = DBManager::getGlobal();
    dbm->insertRepair(rep);

    delete rep;
}
